package ac.beiwo.baas.object.controller;

import ac.beiwo.baas.admin.service.ClazzService;
import ac.beiwo.baas.common.entity.SimpleError;
import ac.beiwo.baas.common.entity.SimpleCode;
import ac.beiwo.baas.common.entity.SimpleResult;
import ac.beiwo.baas.common.service.MasterService;
import ac.beiwo.baas.object.entity.BaasInclude;
import ac.beiwo.baas.object.entity.BaasObject;
import ac.beiwo.baas.object.entity.BaasQuery;
import ac.beiwo.baas.object.entity.BaasSort;
import ac.beiwo.baas.object.service.ObjectService;
import ac.beiwo.baas.user.entity.BaasUser;
import ac.beiwo.baas.user.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Staryet on 15/6/4.
 */
@RestController
@RequestMapping(value = "/object")
public class ObjectController {

    @Autowired
    private ObjectService objectService;
    @Autowired
    private ClazzService clazzService;
    @Autowired
    private MasterService masterService;
    @Autowired
    private UserService userService;
    @Autowired
    private HttpServletRequest request;

    /**
     * 插入对象
     *
     * @param body 对象
     * @param name 类名
     * @return
     * @throws SimpleError
     */
    @RequestMapping(value = "/{name}", method = RequestMethod.POST)
    @ResponseBody
    public SimpleResult insert(@RequestBody String body, @PathVariable String name) throws SimpleError {
        //处理权限
        boolean isMaster = masterService.isMaster(request);
        BaasUser currentUser = userService.getCurrentUser(request);
        //非master权限禁止操作内部类数据
        if (!isMaster && !clazzService.isNameValid(name)) {
            throw new SimpleError(SimpleCode.CLAZZ_NAME_ERROR);
        }
        JSONObject json = (JSONObject) JSON.parse(body);
        BaasObject object = new BaasObject(json);
        //存储对象
        String id = objectService.insert(name, object, currentUser, isMaster);
        SimpleResult result = SimpleResult.success();
        result.putData("id", id);
        return result;
    }

    /**
     * 获取对象
     *
     * @param name 类名
     * @param id   id
     * @return
     * @throws SimpleError
     */
    @RequestMapping(value = "/{name}/{id}", method = RequestMethod.GET)
    @ResponseBody
    public BaasObject get(@PathVariable String name,
                          @PathVariable String id,
                          @RequestParam(required = false) String include) throws SimpleError {
        //处理include
        BaasInclude bassInclude = objectService.getBaasInclude(include);
        //处理权限
        boolean isMaster = masterService.isMaster(request);
        BaasUser currentUser = userService.getCurrentUser(request);
        //获取数据
        BaasObject result = objectService.get(name, id, bassInclude, currentUser, isMaster);
        if (result == null) {
            result = new BaasObject();
        }
        return result;
    }

    /**
     * 查询对象
     *
     * @param name  类名
     * @param where 查询条件
     * @return
     */
    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
    @ResponseBody
    public List<BaasObject> find(@PathVariable String name,
                                 @RequestParam(required = false) String where,
                                 @RequestParam(required = false) String order,
                                 @RequestParam(required = false) String include,
                                 @RequestParam(required = false, defaultValue = "100") int limit,
                                 @RequestParam(required = false, defaultValue = "0") int skip) throws SimpleError {
        //处理查询字段
        JSONObject queryJson = (JSONObject) JSON.parse(where);
        BaasQuery query;
        query = queryJson == null ? null : new BaasQuery(queryJson);
        //处理排序字段
        JSONObject sortJson = (JSONObject) JSON.parse(order);
        BaasSort sort;
        sort = sortJson == null ? null : new BaasSort(sortJson);
        //处理include
        BaasInclude bassInclude = objectService.getBaasInclude(include);
        //处理权限
        boolean isMaster = masterService.isMaster(request);
        BaasUser currentUser = userService.getCurrentUser(request);
        return objectService.list(name, query, sort, bassInclude, limit, skip, currentUser, isMaster);
    }

    /**
     * 获取对象个数
     *
     * @param name  类名
     * @param where 查询条件
     * @return
     */
    @RequestMapping(value = "/{name}/count", method = RequestMethod.GET)
    @ResponseBody
    public SimpleResult count(@PathVariable String name, @RequestParam(required = false) String where)
            throws SimpleError {
        JSONObject queryJson = (JSONObject) JSON.parse(where);
        BaasQuery query;
        if (queryJson == null) {
            query = new BaasQuery();
        } else {
            query = new BaasQuery(queryJson);
        }
        SimpleResult result = SimpleResult.success();
        result.putData("count", objectService.count(name, query));
        return result;
    }

    /**
     * 更新对象
     *
     * @param body 对象
     * @param name 类名
     * @return
     */
    @RequestMapping(value = "/{name}/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public SimpleResult update(@RequestBody String body, @PathVariable String name, @PathVariable String id) throws SimpleError {
        //处理权限
        boolean isMaster = masterService.isMaster(request);
        BaasUser currentUser = userService.getCurrentUser(request);
        //非master权限禁止操作内部类对象
        if (!isMaster && !clazzService.isNameValid(name)) {
            throw new SimpleError(SimpleCode.CLAZZ_NAME_ERROR);
        }
        JSONObject json = (JSONObject) JSON.parse(body);
        BaasObject object = new BaasObject(json);
        objectService.update(name, id, object, currentUser, isMaster);
        return SimpleResult.success();
    }

    /**
     * 原子操作
     *
     * @param body 对象
     * @param name 类名
     * @return
     */
    @RequestMapping(value = "/{name}/{id}/inc", method = RequestMethod.PUT)
    @ResponseBody
    public SimpleResult increment(@RequestBody String body, @PathVariable String name, @PathVariable String id) throws SimpleError {
        //处理权限
        boolean isMaster = masterService.isMaster(request);
        BaasUser currentUser = userService.getCurrentUser(request);
        //非master权限禁止操作内部类对象
        if (!isMaster && !clazzService.isNameValid(name)) {
            throw new SimpleError(SimpleCode.CLAZZ_NAME_ERROR);
        }
        JSONObject json = (JSONObject) JSON.parse(body);
        BaasObject object = new BaasObject(json);

        objectService.increment(name, id, object, currentUser, isMaster);
        return SimpleResult.success();
    }

    /**
     * 删除对象
     *
     * @param name 类名
     * @param id   id
     * @return
     * @throws SimpleError
     */
    @RequestMapping(value = "/{name}/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public SimpleResult delete(@PathVariable String name, @PathVariable String id) throws SimpleError {
        //处理权限
        boolean isMaster = masterService.isMaster(request);
        BaasUser currentUser = userService.getCurrentUser(request);
        //非master权限禁止操作内部类对象
        if (!isMaster && !clazzService.isNameValid(name)) {
            throw new SimpleError(SimpleCode.CLAZZ_NAME_ERROR);
        }
        //删除
        objectService.delete(name, id, currentUser, isMaster);
        return SimpleResult.success();
    }

    /**
     * 根据查询条件删除对象
     *
     * @param name  类名p
     * @param where 查询条件
     * @return
     * @throws SimpleError
     */
    @RequestMapping(value = "/{name}", method = RequestMethod.DELETE)
    @ResponseBody
    public SimpleResult deleteAll(@PathVariable String name, @RequestParam String where) throws SimpleError {
        //TODO 实现批量删除
        return null;
    }

}
